package lar.game.msgParser;


import java.util.Vector;

import lar.system.network.Connection;

public class ParsedMessage 
{
	private String 			str;
	private Vector<String> 	args;
	private boolean 		parsed;		
	private Object 			attachment;
	
	public ParsedMessage(String str)
	{
		attachment = null;
		this.str = new String(str);
		args = new Vector<String>();
		parsed = false;
	}
	
	public static String escapeHTML(String s)
	{
		   StringBuffer sb = new StringBuffer();
		   int n = s.length();
		   for (int i = 0; i < n; i++) {
		      char c = s.charAt(i);
		      switch (c) {        
		         case '\'': sb.append("&#039;");break; 
		         default:  sb.append(c); break;
		      }
		   }
		   return sb.toString();
	}
	
	public void setAttachment(Object obj)
	{
		this.attachment = obj;
	}
	
	public Object getAttachment()
	{
		return attachment;
	}
	
	public int getSize() //including header
	{
		return args.size();
	}
	public void Parse()
	{
		String[] arr = str.split(Strings.DELIMITER);
		for(int i = 0; i < arr.length; i++) args.add(trimSpaces(arr[i]));
		parsed = true;
	}
	
	public String getOriginalString()
	{
		return this.str;
	}
	
	public String argStr(int idx)
	{
		return args.elementAt(idx);
	}
	
	public double argDouble(int idx)
	{
		return Double.parseDouble(argStr(idx));
	}
	
	public int argInt(int idx)
	{
		return Integer.parseInt(argStr(idx));
	}
	
	public boolean testHeader(String str) throws Exception
	{
		if(!parsed) throw new Exception("Server did not parse this message.");
		return args.elementAt(0).equals(str);
	}
	
	private String trimSpaces(String str)
	{
		int i = 0, j = str.length()-1;
		while(i < str.length() && str.charAt(i) == ' ') i++;
		while(j >= 0 && str.charAt(j) == ' ') j--;
		
		return str.substring(i, j+1);
	}
	
	
}
